#include "mainwindow.h"
#include "generalsetstyle.h"
#include "configfile.h"
#include "musicinfo.h"
#include "ui_mainwindow.h"
#include "listmenu.h"


#include <QFile>
#include <QFileInfo>
#include <QLabel>
#include <QMessageBox>
#include <QToolTip>
#include <QFileSystemWatcher>

#include <QFileDialog> //打开文件夹
#include <time.h>

#include <QDebug>
#include <QPropertyAnimation>
#include <QToolButton>


MainWindow::MainWindow(QWidget *parent)
    :QMainWindow(parent), ui(new Ui::MainWindow), music_mode(ORDER_MODE)
{

  ui->setupUi(this);
  setWindowTitle("简单的音乐软件播放器");
  setFixedSize(1000, 600);//设置窗口大小
  srand(time(NULL));//随机种子
  //音乐播放器
  music_player = new QMediaPlayer(this);
  audioOutput = new QAudioOutput;
  music_player->setAudioOutput(audioOutput);
  // 加载配置文件的内容
  LoadConfigFile(ui, this, audioOutput);
  custom_song_list->setFont(qApp->font());
  // 默认加载目录,以及是否加载,和还有是否播放音乐
  Default_Music_Dir=MusicLoadCfg(Default_Music_Dir, &default_isload, &play_music);
  //按钮以及一些组件的初始化
  WidgetInit();
  //默认是否加载音乐路径
  if (default_isload)
  {
    DirPath = Default_Music_Dir;
    loadMusicFileDir(DirPath);
    loadDownLoadSong();
  }
}

void MainWindow::WidgetInit()
{

    qApp->installEventFilter(this);
    setTableViewStyle(ui->music_list);
    setTableViewStyle(ui->download_list);
    //ui->download_list->setStyleSheet(ui->music_list->styleSheet());
    //默认是加载的音乐
    play_song_list=custom_song_list;

    setFocusPolicy(Qt::StrongFocus);

    setButtonStyle(ui->btn_pre, ":/icons/上一首.png", "上一首");
    //判断默认是播放还是暂停
    if(play_music && ui->music_list->model()->rowCount())
        setButtonStyle(ui->btn_play, ":/icons/暂停.png", "播放音乐");
    else
        setButtonStyle(ui->btn_play, ":/icons/播放.png", "暂停音乐");
    setButtonStyle(ui->btn_next, ":/icons/下一首.png", "下一首");
    setButtonStyle(ui->btn_fuct, ":/icons/顺序.png", "顺序模式");
    setButtonStyle(ui->btn_list, ":/icons/音乐列表.png", "音乐列表");
    setButtonStyle(ui->btn_dir, ":/icons/文件夹.png", "加载音乐路径");
    setButtonStyle(ui->btn_playlist, ":/icons/笔记.png", "已有歌单");
    setButtonStyle(ui->btn_set, ":/icons/设置.png", "软件设置");
    if(ui->mute_btn->isChecked())
        setButtonStyle(ui->btn_sound, ":/icons/静音.png", "音量控制");
    else
        setButtonStyle(ui->btn_sound, ":/icons/声音.png", "音量控制");
    //歌曲搜索按键
    //图标设置
    // ui->btn_search->resize(ui->song_search->height(),ui->song_search->height());
    // ui->btn_search->setIcon(QIcon(":/icons/搜索.png"));
    // ui->btn_search->setIconSize(QSize(ui->btn_search->width(), ui->btn_search->height()));
    //自定义播放列表设置
    connect(ui->btn_play, &QPushButton::clicked,this,&MainWindow::handlePlaySlot);
    // 播放模式
    connect(ui->btn_fuct, &QPushButton::clicked, this,
            &MainWindow::handleModeSlot);
    // 下一首
    connect(ui->btn_next, &QPushButton::clicked, this,
            &MainWindow::handleNextSlot);
    // 上一首
    connect(ui->btn_pre, &QPushButton::clicked, this, &MainWindow::handlePreSlot);
    // 文件夹
    connect(ui->btn_dir, &QPushButton::clicked, this, &MainWindow::handleDirSlot);
    // 歌曲列表
    connect(ui->btn_list, &QPushButton::clicked, this,
            &MainWindow::handleListSlot);
    // 双击歌曲列表

    connect(custom_song_list, &QTableView::clicked,
            [=]() {

                play_song_list=custom_song_list;
                //更改封面
                AdjustSongWidget(play_song_list);
                //更改歌曲信息
                SongData(ui,play_song_list);
                startPlayMusic(play_song_list);
            });
    // 歌曲列表
    connect(ui->btn_playlist, &QPushButton::clicked, this,
            &MainWindow::handlePlaylistSolt);
    // 音乐设置
    connect(ui->btn_sound, &QPushButton::clicked, this,
            &MainWindow::handleSoundSet);
    // 设置按钮
    connect(ui->btn_set, &QPushButton::clicked, this,
            &MainWindow::handleSoftwareSet);
    //歌曲搜索栏
    connect(ui->song_search, &QLineEdit::textChanged, this,
            &MainWindow::handleSongSearch);

    //歌词页面按钮
    connect(ui->btn_lrc, &QPushButton::clicked, [this]()
            {
                if(ui->stacked_widget->currentIndex()!=0)//切换到歌词页
                {
                    ui->stacked_widget->setCurrentIndex(0);
                    HideFirstWidget();
                }
                else
                {
                    ui->stacked_widget->setCurrentIndex(1);
                    ShowFirstWidget();
                }
            });
    //正在播放歌曲信息
    connect(ui->lyric_display, &QListWidget::itemClicked,
            [=](QListWidgetItem *item) {
                music_player->setPosition(item->data(Qt::UserRole).toInt());
                ui->lyric_display->scrollToItem(item,QAbstractItemView::PositionAtCenter);
                qDebug()<<ui->lyric_display->row(item)<<"+++++++++++";
            });
    connect(ui->btn_tabbar1, &QPushButton::clicked,[=]
    {
        ui->tabWidget_2->setCurrentIndex(0);
        ui->btn_tabbar1->setChecked(true);
        ui->btn_tabbar2->setChecked(false);
    });
    QTimer::singleShot(100,ui->btn_tabbar1, &QPushButton::animateClick);
    connect(ui->btn_tabbar2, &QPushButton::clicked,[=]{
        ui->tabWidget_2->setCurrentIndex(1);
        ui->btn_tabbar1->setChecked(false);
        ui->btn_tabbar2->setChecked(true);

    });

    // 歌词显示
    // ui->lyric_display->setStyleSheet("QListWidget "
    //                                  "{ "
    //                                  "background-color: transparent;"
    //                                  "color: gray;"
    //                                  "}"
    //                                  "QListWidget::item:selected {"
    //                                  "background-color: transparent;"
    //                                  "color: gray;"
    //                                  "}");
    ui->lyric_display->setCurrentRow(0);

    custom_song_list->setStyleSheet("QTableView {"
                                  "margin: 10px;"
                                  "padding: 3px;"
                                  "gridline-color: transparent;"
                                  "border-radius: 10px;"
                                  "border: 5px solid #4e6e97;"
                                  "}"
                                   "QTableView::item {"
                                   "border-bottom: 1px solid #e0e0e0;"
                                   "}"
                                  "QTableView::item:selected {"
                                  "background-color: #4CAF50;"
                                  "color: white;"
                                  "}");

    custom_song_list->setParent(this);
    custom_song_list->resize(300,400);
    custom_song_list->hide();
    QStandardItemModel *model = new QStandardItemModel();
    model->setColumnCount(4);
    QStringList headers;
    headers <<" "<<"歌曲名"<<"时长"<<"操作";
    model->setHorizontalHeaderLabels(headers);
    custom_song_list->setShowGrid(false);
    custom_song_list->setModel(model);
    custom_song_list->horizontalHeader()->setVisible(true);
    custom_song_list->verticalHeader()->setVisible(false);
    custom_song_list->setEditTriggers(QAbstractItemView::NoEditTriggers);
    custom_song_list->setSelectionBehavior(QAbstractItemView::SelectRows);
    custom_song_list->setIconSize(QSize(32,32));
    custom_song_list->horizontalHeader()->setSectionsClickable(false);
    custom_song_list->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); // 根据内容调整
    custom_song_list->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); // 根据内容调整
    custom_song_list->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);         // 拉伸填充可用空间
    custom_song_list->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Fixed);
    custom_song_list->horizontalHeader()->resizeSection(0, 40);
    custom_song_list->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    custom_song_list->viewport()->installEventFilter(this);
    custom_song_list->setAlternatingRowColors(true); // 启用交替行颜色
    custom_song_list->setAutoScroll(false);

    //ui->btn_tabbar1->setChecked(true);

    //ui->music_slider->setStyleSheet(":/style.qss");

    //
    ui->btn_lrc->setToolTip("点击显示打开歌词播放界面");
    ui->btn_lrc->setToolTipDuration(2000);
    //声音设置隐藏
    ui->sound_widget->hide();
    //tab标签页设置成黑色


    ui->tabWidget->setCurrentIndex(0);

    //起始页
    ui->tabWidget_2->setCurrentIndex(0);
    //不显示标签
    ui->tabWidget_2->tabBar()->setVisible(false);
    //ui->tabWidget_2->tabBar()->setVisible(false);
    //默认是否加载音乐列表
    if (!default_isload)
    {
        //除了歌词都隐藏

        ui->music_list->hide();
        ui->pic_display->hide();
        ui->song_data->hide();
        // ui->btn_search->hide();
        ui->song_search->hide();
        ui->dir_path->hide();
    }

}


//设置tableview样式
void MainWindow::setTableViewStyle(QTableView *tableview)
{
    QHeaderView *horizontalHeader = tableview->horizontalHeader();
    horizontalHeader->setSectionResizeMode(QHeaderView::ResizeToContents); // 根据内容调整
    horizontalHeader->setSectionResizeMode(QHeaderView::Stretch);         // 拉伸填充可用空间
    tableview->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); // 根据内容调整
    QStandardItemModel *model = new QStandardItemModel();
    model->setColumnCount(6);
    QStringList headers;
    headers << " " << "歌曲" << "艺术家" << "专辑"<<"时长"<<"操作";
    model->setHorizontalHeaderLabels(headers);
    tableview->setModel(model);
    tableview->setShowGrid(false);
    tableview->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Fixed);
    tableview->horizontalHeader()->resizeSection(0, 40);
    tableview->verticalHeader()->setFixedWidth(35);
    tableview->setEditTriggers(QAbstractItemView::NoEditTriggers);//不可编辑
    tableview->setSelectionBehavior(QAbstractItemView::SelectRows);//一次选一行
    tableview->setAlternatingRowColors(true);//颜色交替
    tableview->viewport()->installEventFilter(this);
    connect(tableview, &QTableView::clicked,
            [=]() {

                play_song_list=tableview;
                //更改封面
                AdjustSongWidget(play_song_list);
                //更改歌曲信息
                SongData(ui,play_song_list);
                startPlayMusic(play_song_list);
            });

}
// 按钮样式设置以及事件(下面也是)
void MainWindow::setButtonStyle(QPushButton *button, const QString filename,
                                QString tooltip) {
  button->setFixedSize(50, 50);
  button->setIcon(QIcon(filename));
  button->setIconSize(QSize(button->width() - 5, button->height() - 5));
  // 设置背景颜色为透明，不过好像在linux上没法用,背景调成黑色了
  // 悬停变化
  button->setCursor(Qt::PointingHandCursor);
  button->setStyleSheet(R"(
                            QPushButton
                            {
                                border-radius: 10px;
                                border: none;
                            }
                            QPushButton:hover
                            {
                                background: rgba(0,0,0,50);/*悬停时背景颜色*/
                            }
                        )");
  button->setToolTipDuration(2000); // 2秒后消失
  //弹窗提示
  button->setToolTip(tooltip);

  // 下面是动画
  // 按钮点击动画添加
  connect(button, &QPushButton::pressed, [=]() {
    QPropertyAnimation *anim = new QPropertyAnimation(button, "geometry");
    anim->setDuration(10);//动画持续时间
    anim->setStartValue(button->geometry());
    anim->setEndValue(button->geometry().adjusted(-1, -1, -1, -1));
    anim->start(QAbstractAnimation::DeleteWhenStopped);
  });
  connect(button, &QPushButton::released, [=]() {
    QPropertyAnimation *anim = new QPropertyAnimation(button, "geometry");
    anim->setDuration(10);//动画持续时间
    anim->setStartValue(button->geometry());
    anim->setEndValue(button->geometry().adjusted(1, 1, 1, 1));
    anim->start(QAbstractAnimation::DeleteWhenStopped);
  });
}

void MainWindow::CustomSetButtonStyle(QPushButton *button,const QString filename,int iconsize,
                          QString tooltip)
{

    button->setFixedSize(iconsize, iconsize);
    button->setIcon(QIcon(filename));
    button->setIconSize(QSize(button->width() - 5, button->height() - 5));
    // 设置背景颜色为透明，不过好像在linux上没法用,背景调成黑色了
    // 悬停变化
    button->setCursor(Qt::PointingHandCursor);
    button->setStyleSheet(R"(
                            QPushButton
                            {
                                border-radius: 10px;
                                border: none;
                            }
                            QPushButton:hover
                            {
                                background: rgba(0,0,0,50);/*悬停时背景颜色*/
                            }
                        )");
    button->setToolTipDuration(2000); // 2秒后消失
    //弹窗提示
    button->setToolTip(tooltip);

    // 下面是动画
    // 按钮点击动画添加
    connect(button, &QPushButton::pressed, [=]() {
        QPropertyAnimation *anim = new QPropertyAnimation(button, "geometry");
        anim->setDuration(10);//动画持续时间
        anim->setStartValue(button->geometry());
        anim->setEndValue(button->geometry().adjusted(-1, -1, -1, -1));
        anim->start(QAbstractAnimation::DeleteWhenStopped);
    });
    connect(button, &QPushButton::released, [=]() {
        QPropertyAnimation *anim = new QPropertyAnimation(button, "geometry");
        anim->setDuration(10);//动画持续时间
        anim->setStartValue(button->geometry());
        anim->setEndValue(button->geometry().adjusted(1, 1, 1, 1));
        anim->start(QAbstractAnimation::DeleteWhenStopped);
    });
}
//播放音乐（预备）
void MainWindow::startPlayMusic(QTableView *tableview)
{

    QModelIndex currentIndex = tableview->currentIndex();
    int currentRow = currentIndex.row(); // 获取行号
    //获取模型
    QStandardItemModel* model = qobject_cast<QStandardItemModel*>(tableview->model());
    QStandardItem *item =model->item(currentRow,0);//一开始是0

    //mp3文件和lrc文件路径
    QString  musicAbsPath =item->data(Qt::UserRole+4).toString()+".mp3";
    QString musicLyricsPath =item->data(Qt::UserRole+4).toString()+".lrc";


    //如果文件没有了,这里特指是待播放歌曲列表
    if(!QFile::exists(musicAbsPath))
    {
        QMessageBox::information(this, "","该歌曲不存在");
        music_player->stop();
        tableview->model()->removeRow(currentRow);
        if(currentRow==tableview->model()->rowCount())
        {
            currentRow--;
        }
        qDebug()<<currentRow;
        if(currentRow>=0)
        {
            tableview->selectRow(currentRow);
            item =model->item(currentRow,0);//一开始是0
            qDebug()<<currentRow;
            musicAbsPath =item->data(Qt::UserRole+4).toString()+".mp3";
            musicLyricsPath =item->data(Qt::UserRole+4).toString()+".lrc";
            //更改封面
            AdjustSongWidget(play_song_list);
            //更改歌曲信息
            SongData(ui,play_song_list);
        }

    }




    //music_player->pause();
    //加载音乐和歌词
    music_player->setSource(QUrl::fromLocalFile(musicAbsPath));
    readLyricsFile(musicLyricsPath);

    qDebug()<<musicAbsPath<<"+++++++++++";

    ui->lyric_display->setCurrentRow(0);
    ui->music_slider->setValue(0);
    //歌词标题
    ui->song_title->move(0,0);
    ui->song_title->resize(ui->lyric_display->width(),ui->lyric_display->y());
    ui->song_title->setText(ui->song_name->text());
    if (play_music) // 导入音乐的时候不播放
    {
        //播放音乐
        handlePlaySlot();
    }
}

// 播放处理
void MainWindow::handlePlaySlot() {

   //别管是干嘛的
   dir_change=false;
  //看有没有歌
   if (!play_song_list->model()->rowCount())
  {
        QToolTip::showText(QCursor::pos(), "当前没有音乐无法播放", nullptr, QRect(),
                        2000);
  }
  else
  {
    if (music_player->playbackState() == QMediaPlayer::PlayingState)
    {
        //解决暂停不流畅的问题
        music_player->setPosition(ui->music_slider->value());
        music_player->pause();
        ui->btn_play->setIcon(QIcon(":/icons/播放.png"));
        ui->btn_play->setToolTipDuration(2000); // 2秒后消失
        ui->btn_play->setToolTip("播放音乐");
    }
    else
    {
      music_player->play();
      //解决暂停时间过播放时有一段时间没有声音的问题
      music_player->setPosition(ui->music_slider->value());
      ui->btn_play->setIcon(QIcon(":/icons/暂停.png"));
      ui->btn_play->setToolTipDuration(2000); // 2秒后消失
      ui->btn_play->setToolTip("暂停音乐");
    }
  }
}
// 播放模式
void MainWindow::handleModeSlot() {
  switch (music_mode) {
  // 顺序
  case ORDER_MODE:
    music_mode = RANDOM_MODE;
    ui->btn_fuct->setIcon(QIcon(":/icons/随机.png"));
    ui->btn_fuct->setToolTip("随机模式");
    ui->btn_fuct->setToolTipDuration(2000);
    QToolTip::showText(QCursor::pos(), "随机模式", nullptr, QRect(), 2000);
    break;
  // 随机
  case RANDOM_MODE:
    music_mode = CIRCLE_MODE;
    ui->btn_fuct->setIcon(QIcon(":/icons/循环.png"));
    ui->btn_fuct->setToolTip("循环模式");
    ui->btn_fuct->setToolTipDuration(2000);
    QToolTip::showText(QCursor::pos(), "循环模式", nullptr, QRect(), 2000);
    break;
  // 循环
  case CIRCLE_MODE:
    music_mode = ORDER_MODE;
    ui->btn_fuct->setIcon(QIcon(":/icons/顺序.png"));
    ui->btn_fuct->setToolTip("顺序模式");
    ui->btn_fuct->setToolTipDuration(2000);
    QToolTip::showText(QCursor::pos(), "顺序模式", nullptr, QRect(), 2000);
    break;
  }
}
// 下一首
void MainWindow::handleNextSlot()
{

  int currentRow = play_song_list->currentIndex().row();
  qDebug()<<currentRow;
  int next = 0;
  int compare = 0; // 用来比对,判断下一首是否相同
  switch (music_mode) {
  case ORDER_MODE:
    if (currentRow != play_song_list->model()->rowCount() - 1)
      next = currentRow + 1;
    // 否则就是next的默认值
    break;
  case RANDOM_MODE:
    do {
      next = rand() % (play_song_list->model()->rowCount());
      compare++;
    } while (next == currentRow && compare <= 3);
    break;
  case CIRCLE_MODE:
    QToolTip::showText(QCursor::pos(), "当前处于循环播放模式,重复播放", this,
                       QRect(), 2000);
    next = currentRow;
    break;
  }
  if (play_song_list->model()->rowCount())
  {
    qDebug()<<currentRow<<"+++";
    QModelIndex currentIndex = play_song_list->currentIndex();
    int currentRow = currentIndex.row(); // 获取行号
    qDebug()<<next;
    QModelIndex index = play_song_list->model()->index(next, 0); // 第row行，第0列
    int row=index.row();
      // 设置当前索引
    play_song_list->setCurrentIndex(index);
    qDebug()<<row<<currentRow;
    //更改封面
    AdjustSongWidget(play_song_list);
    SongData(ui,play_song_list);
    startPlayMusic(play_song_list);
  } else
    QToolTip::showText(QCursor::pos(), "当前列表无音乐可放", nullptr, QRect(),
                       3000);
}
// 上一首
void MainWindow::handlePreSlot() {
  int currentRow = play_song_list->currentIndex().row();
  int pre = play_song_list->model()->rowCount() - 1;
  int compare = 0; // 用来比对,判断下一首是否相同
  switch (music_mode) {
  case ORDER_MODE:
    if (currentRow != 0)
      pre = currentRow - 1;
    // 否则就是最后一个了
    break;
  case RANDOM_MODE:
    do {
      pre = rand() % (play_song_list->model()->rowCount());
      compare++;
    } while (pre == currentRow && compare <= 3);
    break;
  case CIRCLE_MODE:
    QToolTip::showText(QCursor::pos(), "当前处于循环播放模式,重复播放", nullptr,
                       QRect(), 2000);
    pre = currentRow;
    break;
  }
  if (play_song_list->model()->rowCount()) {
      QModelIndex index = play_song_list->model()->index(pre, 0); // 第row行，第0列

      // 设置当前索引
      play_song_list->setCurrentIndex(index);
    //更改封面
    AdjustSongWidget(play_song_list);
    //SongData(pre,ui,play_song_list);
    //更改歌曲信息
    startPlayMusic(play_song_list);
  } else
    QToolTip::showText(QCursor::pos(), "当前列表无音乐可放", nullptr, QRect(),
                       3000);
}
// 按钮初始化

// 列表动画效果添加
void MainWindow::handleListSlot()
{
    QPoint buttonPos = ui->btn_list->mapToGlobal(QPoint(0, 0));
    custom_song_list->move(buttonPos.x(),buttonPos.y()-custom_song_list->height());
    if (custom_song_list->isHidden())
    {
        custom_song_list->show();//列表
    }
    else
    {
      custom_song_list->hide();
    }
}
// 列表出现动画
void MainWindow::ListAppear(QListWidget *listWidget) {
  QPropertyAnimation animation(listWidget, "pos");
  // 持续时间,这是一个宏定义,在mainwindow.h中
  animation.setDuration(AnimationLastTime);
  animation.setStartValue(QPoint(this->width(), ui->music_list->y()));
  animation.setEndValue(
      QPoint(this->width() - ui->music_list->width(), ui->music_list->y()));
  animation.start();

  QEventLoop loop;
  connect(&animation, &QPropertyAnimation::finished, &loop, &QEventLoop::quit);
  loop.exec();
}
// 列表隐藏动画
void MainWindow::ListDisAppear(QListWidget *listWidget) {
  QPropertyAnimation animation(listWidget, "pos");

  animation.setDuration(AnimationLastTime);
  animation.setStartValue(
      QPoint(this->width() - ui->music_list->width(), ui->music_list->y()));
  animation.setEndValue(QPoint(this->width(), ui->music_list->y()));
  animation.start();

  QEventLoop loop;
  connect(&animation, &QPropertyAnimation::finished, &loop, &QEventLoop::quit);
  loop.exec();
}
// // 设置播放器背景
void MainWindow::setBackground(const QString filename) {

    // 加载图片
    QPixmap pixmap(filename);
    if (pixmap.isNull()) {
        qWarning() << "Failed to load image:" << filename;
        return;
    }

    // 获取窗口尺寸
    QSize windowSize = this->size();

    // 高质量缩放图片
    QPixmap scaledPixmap = pixmap.scaled(windowSize,
                                         Qt::KeepAspectRatioByExpanding,
                                         Qt::SmoothTransformation);

    // 裁剪中心部分
    if (scaledPixmap.width() > windowSize.width() ||
        scaledPixmap.height() > windowSize.height()) {
        QRect sourceRect((scaledPixmap.width() - windowSize.width()) / 2,
                         (scaledPixmap.height() - windowSize.height()) / 2,
                         windowSize.width(), windowSize.height());
        scaledPixmap = scaledPixmap.copy(sourceRect);
    }

    // 应用模糊效果（可选）
    QGraphicsBlurEffect *blurEffect = new QGraphicsBlurEffect;
    blurEffect->setBlurRadius(100); // 设置模糊半径

    // 创建临时部件应用模糊效果
    QWidget *tempWidget = new QWidget;
    tempWidget->setGraphicsEffect(blurEffect);
    tempWidget->setFixedSize(scaledPixmap.size());

    // 渲染模糊效果到图片
    QPixmap blurredPixmap(scaledPixmap.size());
    blurredPixmap.fill(Qt::transparent);
    QPainter painter(&blurredPixmap);
    tempWidget->render(&painter);
    painter.drawPixmap(0, 0, scaledPixmap);
    delete tempWidget;

    // 设置背景图片
    QPalette palette;
    palette.setBrush(QPalette::Window, QBrush(blurredPixmap));
    this->setPalette(palette);
    this->setAutoFillBackground(true);
}
// 进度条联动
void MainWindow::DisplaySlider(QSlider *progressSlider, QMediaPlayer *player) {

  // 连接播放器位置变化信号到进度条

    progressSlider->installEventFilter(this);
    progressSlider->setCursor(Qt::PointingHandCursor);
    connect(player, &QMediaPlayer::positionChanged, this, [=](qint64 position) {
          // 防止进度条拖动时冲突
          if (!progressSlider->isSliderDown()) {
              progressSlider->setValue(position);
          }
          if(player->position()>player->duration())
          {
              qDebug()<<"错误错误";
          }
           ui->music_slider->setToolTip("当前时间:"+QString::number(ui->music_slider->value()/1000)+"s");
          // 更新时间
          if(!dir_change)
              UpdateTime(player);
      });

   //先断开,防止重复连接
   disconnect(progressSlider, &QSlider::sliderReleased, nullptr, nullptr);
    //连接进度条拖动信号到播放器
    //拖动的完结束的时候改变进度
   connect(progressSlider, &QSlider::sliderReleased,player,
          [=]()
        {
            //改变歌曲进度
            SilderRelease(player,progressSlider);
        });

  // 连接媒体加载完成信号
  connect(player, &QMediaPlayer::durationChanged, this,
          [=](qint64 duration) { progressSlider->setRange(0, duration); });
}
void MainWindow::SilderRelease(QMediaPlayer *player,QSlider *progressSlider)
{
    player->setPosition(progressSlider->value());
    int index=0;
    qint64 pre= ui->lyric_display->item(index)->data(Qt::UserRole).toInt();
    qint64 next=ui->lyric_display->item(index+1)->data(Qt::UserRole).toInt();
    //进度条后退
    if (player->position() < ui->lyric_display->currentItem()->data(Qt::UserRole).toInt())
    {
        //移动到开头
        if(pre>=player->position())
            ui->lyric_display->setCurrentRow(index);
        else
        {
            //关键
            while(!(pre<player->position() && next>player->position()))
            {
                index++;
                pre= ui->lyric_display->item(index)->data(Qt::UserRole).toInt();
                next=ui->lyric_display->item(index+1)->data(Qt::UserRole).toInt();
                //qDebug()<<pre<<player->position()<<next;
            }
            //qDebug()<<index;
            ui->lyric_display->setCurrentRow(index);
        }

    }
    //进度条快进
    if (player->position() > ui->lyric_display->currentItem()->data(Qt::UserRole).toInt())
    {

        if(ui->lyric_display->currentRow()-1>=0)
            index=ui->lyric_display->currentRow()-1;
        //快进到结尾
        if(player->position()>=ui->lyric_display->item(ui->lyric_display->count()-1)->data(Qt::UserRole).toInt())
            ui->lyric_display->setCurrentRow(ui->lyric_display->count()-1);
        else
        {
            //qDebug()<<index<<"------------------";
            //关键
            while(!(pre < player->position() && next>player->position()))
            {
                index++;
                pre= ui->lyric_display->item(index)->data(Qt::UserRole).toInt();
                next=ui->lyric_display->item(index+1)->data(Qt::UserRole).toInt();
                //qDebug()<<pre<<player->position()<<next;
            }
            //qDebug()<<index;
            ui->lyric_display->setCurrentRow(index);

        }
    }
}
// 时间显示更新
void MainWindow::UpdateTime(QMediaPlayer *player) {
  // 获取当前时长
  qint64 currentPosition = player->position();
  QListWidgetItem *curitem=nullptr;
  qint64 CurItemRow;

    // 在某个范围内,歌词随音乐进度同步滚动
    if (currentPosition > ui->lyric_display->currentItem()->data(Qt::UserRole).toInt())
    {
          //记录当前行
          CurItemRow=ui->lyric_display->currentRow();
          curitem=ui->lyric_display->item(CurItemRow);
          ui->lyric_display->scrollToItem(curitem,QAbstractItemView::PositionAtCenter);
          //用于还原字体
          //调整播放的字体大小以及背景
          QFont curfont;
          QFont defaultFont = QApplication::font();
          int pointSize = defaultFont.pointSize();
          defaultFont.setPointSize(pointSize + 5);
          defaultFont.setBold(true);
          //设置先还原其他歌词的样式
          ClearLyricStyle(ui->lyric_display,ui->lyric_display->count());
          curitem->setForeground(QBrush(0x5ed698));
          curitem->setFont(defaultFont);
          //右下角显示歌词如果歌词过长就以...省略末尾的
          QFontMetrics  fontMetrics(ui->song_lrc->font());
          ui->song_lrc->setText(fontMetrics.elidedText(curitem->text(),Qt::ElideRight,300));
          // 如果没有歌词了就停止
          if (ui->lyric_display->count()!= ui->lyric_display->currentRow() + 1)
              ui->lyric_display->setCurrentRow(ui->lyric_display->currentRow() + 1);
    }
  // 进度处理
  //  转换为秒
  QString currentSeconds =
      QTime(0, 0).addMSecs(currentPosition).toString("mm:ss");
  // 获取总时长（毫秒）
  qint64 totalDuration = player->duration();
  // 转换为秒
  QString totalSeconds = QTime(0, 0).addMSecs(totalDuration).toString("mm:ss");
  ui->time_display_cur->setText(currentSeconds);
  ui->time_display_tot->setText(totalSeconds);
  if (currentSeconds == totalSeconds) // 自动播放下一首
  {
      player->pause();
      ui->music_slider->setValue(0);
      handleNextSlot();
  }

}
// 音乐目录选择
void MainWindow::handleDirSlot()
{
  //如果弹出的目录选择对话框点❌或者取消的话会返回结果为空""
  QString dirpath = QFileDialog::getExistingDirectory(
      this,                 // 父窗口
      "选择音乐文件的路径", // 对话框标题
      QDir::currentPath(),  // 默认打开路径
      QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
  // 加载音乐路径
  if (!dirpath.isEmpty())
  {
      DirPath=dirpath;
      play_music = false;
      loadMusicFileDir(DirPath);
      int music_number = ui->music_list->model()->rowCount();
      QString message;
      if (music_number)
          message = "导入成功,共导入" + QString::number(music_number) + "首音乐";
      else {
          message = "当前目录一个mp3文件都没有";
      }
      QMessageBox::information(this, "加载音乐路径", message);
  }
}
// 设置音乐目录加载路径
void MainWindow::loadMusicFileDir(QString DirPath) {
  //音乐暂停
  music_player->pause();
  // 歌词清除
  ui->lyric_display->clear();
  // 歌曲列表清除
  ui->music_list->model()->removeRows(0,ui->music_list->model()->rowCount());
  //custom_song_list->model()->removeRows(0,custom_song_list->model()->rowCount());
  //清空进度
  ui->music_slider->setValue(0);
  ui->song_search->clear();
  // 加载目录
  QDir dir(DirPath);
  if (dir.exists() == false && !default_isload) {
    QMessageBox::warning(this, "文件夹", "文件夹打开失败");
    return;
  }
  else
  {
    default_isload = true;
  }
  // 显示该目录下所有的mp3文件
  QFileInfoList filelist = dir.entryInfoList(QDir::Files);
  for (auto element : filelist)
  {
    if (element.suffix() == "mp3") {
        QString filepath = DirPath + QDir::separator() + element.baseName();
        QStandardItemModel* model = qobject_cast<QStandardItemModel*>(ui->music_list->model());
        int newRow = model->rowCount();
        model->insertRow(newRow);//最后一行

        QStandardItem *item =model->item(newRow,0);//一开始是0
        if (!item) {
            item = new QStandardItem();
            model->setItem(newRow, 0, item);

        }
          // 获取歌曲文件自带的图片(数据单元)
        MusicMetaData musicdata = getMusicData(filepath+".mp3",false);
        musicdata.filepath=filepath;
        QImage image = musicdata.image;
        QPixmap pixmap = QPixmap::fromImage(image);
        // 添加图片
        item->setToolTip(element.baseName());
        if(!pixmap.isNull())
            item->setIcon(QIcon(pixmap));
        else
            item->setIcon(QIcon(":/icons/空图片.png"));
        QStringList musicinfo;
        //标题,艺术家,专辑,时长,路径
        musicinfo<<musicdata.title
                  <<musicdata.author
                  <<musicdata.albumTitle
                  <<musicdata.duration
                  <<musicdata.filepath;
        //可以从每个歌曲中获取“标题”等信息

        for(int i=0;i<musicinfo.count();i++)
        {
            item->setData(musicinfo[i],Qt::UserRole + i);
            //qDebug()<<newRow<<item->data(Qt::UserRole + i).toString();
        }
        //歌曲名称
        for(int i=1;i<model->columnCount()-1;i++)
        {
            item =model->item(newRow,i);
            if (!item) {
                item = new QStandardItem();
                model->setItem(newRow,i, item);
            }
            item->setText(musicinfo[i-1]);
            item->setToolTip(musicinfo[i-1]);
            item->setTextAlignment(Qt::AlignCenter);
        }
        item =model->item(newRow,model->columnCount());
        QWidget *widget = new QWidget();
        QHBoxLayout *layout = new QHBoxLayout(widget);
        // 创建播放按钮
        QPushButton *button = new QPushButton();
        layout->addWidget(button);

        QString collectpath=QDir::currentPath()+QDir::separator()+"我的收藏"+QDir::separator()+element.baseName()+".mp3";
        if(QFile::exists(collectpath))
            CustomSetButtonStyle(button,":/icons/已收藏.png",25,"取消收藏");
        else
            CustomSetButtonStyle(button,":/icons/未收藏.png",25,"收藏");
        ui->music_list->setIndexWidget(model->index(newRow, 5), widget);
        //点小红心收藏功能
        connect(button, &QPushButton::clicked,
                [DirPath,this, button]() {
                    //添加到歌单的功能
                    //通过获取与按钮同在一起的标签的序号改变当前行
                    QPoint buttonPos = button->mapTo(ui->music_list, QPoint(0, 0));
                    int row = ui->music_list->rowAt(buttonPos.y());
                    //点击最后一行的时候显示的行数是-1,我也不知道怎么回事
                    if(row==-1)
                       row=ui->music_list->model()->rowCount();
                    row--;
                    bool iscollect=CollectSelect(ui->music_list,DirPath , this, false, "",row);
                    if(iscollect)//还未收藏
                    {
                        CustomSetButtonStyle(button,":/icons/已收藏.png",25,"取消收藏");
                    }
                    else//已经收藏,然后取消收藏
                    {
                        CustomSetButtonStyle(button,":/icons/未收藏.png",25,"收藏");
                        qDebug()<<ui->music_list->currentIndex().row()<<"+++++++++++";
                        DeleteSong(ui->music_list, DirPath, this,false,row);
                        if(music_player->isPlaying() && play_song_list==ui->music_list
                            && row==ui->music_list->currentIndex().row())
                        {
                            AdjustSongWidget(play_song_list);
                            //更改歌曲信息
                            SongData(ui,play_song_list);
                            startPlayMusic(play_song_list);
                        }
                    }
                });
    }
  }
  //加载音乐的时候按钮设置成播放按钮（三角）
  setButtonStyle(ui->btn_play, ":/icons/播放.png", "播放音乐");
  //如果有歌曲
  if (ui->music_list->model()->rowCount())
  {
    ui->dir_path->show();
    QFontMetrics fontMetrics(ui->dir_path->font());
    ui->dir_path->setText(fontMetrics.elidedText("加载路径："+DirPath, Qt::ElideRight,ui->dir_path->width()));
    ui->dir_path->setToolTip(DirPath);
    //歌词默认为第一行
    ui->lyric_display->setCurrentRow(0);
    //歌曲默认是第一个
    ui->music_list->setCurrentIndex(ui->music_list->model()->index(0, 0));

    //导入歌曲到待播放列表
    int cur_row=0;//记住导入前选择的行号
    if(custom_song_list->model()->rowCount()>0)//如果不是第一次倒入
    {
        //记住导入前选择的行号
        cur_row=custom_song_list->currentIndex().row();
        //移动到末尾
        custom_song_list->selectRow(custom_song_list->model()->rowCount()-1);
    }
    for (int index = ui->music_list->model()->rowCount()-1 ; index >=0; index--)
    {
        LoadSongLayout(ui->music_list,custom_song_list,index);
    }
    if(cur_row>=0)
        custom_song_list->selectRow(cur_row);
    else
        custom_song_list->setCurrentIndex(custom_song_list->model()->index(0, 0));




    //加载歌曲信息
    MusicInfo();
    // 进度条显示与连接
    DisplaySlider(ui->music_slider, music_player);
    //确认加载了音乐列表
    dir_change=true;
    startPlayMusic(ui->music_list);
    // 音乐加载完毕后startPlayMusic()函数就能使用handlePlaySlot()函数了 play_music = true;
    play_music = true;
    //音乐列表出现
    ui->music_list->show();
    //音乐列表是否展示
    // 列表标签下的文件路径显示

    //ui->dir_path->adjustSize();
    //ui->dir_path->show();
    // 音乐列表菜单栏
    SetListMenu(DirPath);

  }
  else //指定目录下没有歌曲
  {
    //隐藏歌曲信息
    ui->pic_display->hide();
    ui->song_data->hide();
    ui->dir_path->setText("加载路径："+DirPath);
    disconnect(music_player, &QMediaPlayer::positionChanged, this, nullptr);
    ui->time_display_cur->setText("00:00");
    ui->time_display_tot->setText("00:00");
  }
  //
}

void MainWindow::loadMusicFileList()
{
    QString target_dir="../待播放";
    QDir dir(target_dir);
    if (dir.exists() == false && !default_isload) {
        QMessageBox::warning(this, "文件夹", "文件夹打开失败");
        return;
    }
    // 显示该目录下所有的mp3文件
    QFileInfoList filelist = dir.entryInfoList(QDir::Files);
    for (auto element : filelist)
    {
        if (element.suffix() == "mp3")
        {
            QString filepath = target_dir + QDir::separator() + element.baseName();
            // 获取歌曲文件自带的图片(数据单元)
            MusicMetaData musicdata = getMusicData(filepath+".mp3",false);
            MusicMetaDataBase metaData;
            metaData.title=musicdata.title;
            metaData.author=musicdata.author;
            metaData.duration=musicdata.duration;
            metaData.filename=element.baseName();
            metaData.filepath=filepath;
            // 添加图片
            //LoadSongLayout(metaData,this,custom_song_list);
        }
    }
}

// 歌词(lyr)文件处理
void MainWindow::readLyricsFile(const QString lyricsFilePath) {

    ui->lyric_display->clear();
    QFile file(lyricsFilePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "无法打开文件:" << lyricsFilePath;
    }
    QTextStream in(&file);
    in.setEncoding(QStringConverter::Utf8);
    // 正则表达式匹配时间标签和歌词
    QRegularExpression regex("(\\[[0-9]{2}:[0-9]{2}\\.[0-9]{1,3}\\]|)" // 时间标签
                             "([^\\[]*)"                             // 歌词文本
                             );
    while (!in.atEnd()) {
        QString line = in.readLine().trimmed();
        // 跳过空行
        if (line.isEmpty())
            continue;
        // 匹配所有时间标签和歌词
        QRegularExpressionMatchIterator i = regex.globalMatch(line);
        while (i.hasNext()) {
            QRegularExpressionMatch match = i.next();
            QString timeTag = match.captured(1);         // 匹配的时间标签
            QString lyric = match.captured(2).trimmed(); // 歌词文本
            if (!lyric.isEmpty() && !lyric.contains("]")) {
                // 格式化为 [mm:ss]歌词 的样式
                QListWidgetItem *item = new QListWidgetItem(lyric);
                // 设置文本水平垂直居中
                item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
                //播放歌词当前时间嵌入到歌词中
                item->setData(Qt::UserRole, readLyricsTime(timeTag));
                //显示提示弹窗
                item->setToolTip("跳转到:" + QString::number(readLyricsTime(timeTag) / 1000) + "秒");
                //两秒后消失
                ui->lyric_display->setToolTipDuration(2000);
                ui->lyric_display->addItem(item);
            }
        }
    }
    file.close();
}
//歌词时间
int MainWindow::readLyricsTime(QString timeTag)
{
    QRegularExpression timeRegex("\\[(\\d{2}):(\\d{2})(?:\\.(\\d{2,3}))?\\]");
    // 进行匹配
    QRegularExpressionMatch match = timeRegex.match(timeTag);
    int totalMs;
    {
        // 提取各部分数字
        QString minutes = match.captured(1);      // "00"
        QString seconds = match.captured(2);      // "01"
        QString milliseconds = match.captured(3); // "300"
        // 转换为数值类型
        int min = minutes.toInt();                                  // 0
        int sec = seconds.toInt();                                  // 1
        int ms = milliseconds.isEmpty() ? 0 : milliseconds.toInt(); // 300
        // 计算总毫秒数
        totalMs = min * 60000 + sec * 1000 + ms;
    }
    return totalMs;
}
//歌词以播放的歌词样式重置
void MainWindow::ClearLyricStyle(QListWidget* listWidget,int index)
{
    for (int i = 0; i < index; ++i) {
          QListWidgetItem* item = listWidget->item(i);
          //item->setBackground(QBrush()); // 重置为默认背景色
          QFont font = item->font();     // 获取当前字体
          font.setBold(false);
          font.setPointSize(listWidget->font().pointSize());// 设置新（重置）字体大小
          item->setFont(font);         // 应用字体
          item->setForeground(Qt::gray);
    }
}
// 切换已有歌单功能
void MainWindow::handlePlaylistSolt()
{
  QDialog dialog(this);
  dialog.setWindowTitle("我的歌单列表"); // 设置弹窗名称
  QGridLayout *gridLayout = new QGridLayout(&dialog);
  //获取当前路径下的所有目录
  QStringList music_list = MusicList();
  int count = music_list.count();
  // 批量创建按钮
  QList<QPushButton *> buttons;
  // 排列分布
  int row = 0, column = 0;
  for (int i = 0; i < count; ++i) {
    QPushButton *btn = new QPushButton(QString(music_list[i]).arg(i));
    buttons.append(btn);
    // gridLayout->addWidget(btn,0,i);
    if (column > 2) {
      row += 1;
      column = 0;
    }
    gridLayout->addWidget(btn, row, column);
    column++;
  }
  //判断是否处于当前目录
  for(int i=0;i<music_list.count();i++)
  {
      QString tmp_dir=QDir::currentPath() + QDir::separator() + music_list[i];
      if(DirPath==tmp_dir)
      {
          buttons[i]->setDisabled(true);
          buttons[i]->setToolTip("当前处于此歌单");
      }
      else
      {
          buttons[i]->setDisabled(false);
      }
  }
  //遍历添加事件
  for (int i = 0; i < count; i++) {
    connect(buttons[i], &QPushButton::clicked,
            [music_list, buttons, i, this, &dialog]() {
              QString target_list = music_list[i];
              DirPath = QDir::currentPath() + QDir::separator() + target_list;
              // buttons[*cur_dir]->setDisabled(false);
              // buttons[i]->setDisabled(true);
              // *cur_dir=i;
              play_music = false;//导入的时候不自动播放音乐
              dialog.accept();
              loadMusicFileDir(DirPath);

            });
  }
  dialog.adjustSize();
  dialog.setMinimumWidth(300);
  dialog.exec();
}
//隐藏组件
void MainWindow::HideFirstWidget()
{

    //ui->btn_list->hide();
    ui->btn_dir->hide();
    custom_song_list->hide();

}
//显示组件
void MainWindow::ShowFirstWidget()
{

    //ui->btn_list->show();
    ui->btn_dir->show();

}
//切换歌曲的时候需要改变的组件
void MainWindow::AdjustSongWidget(QTableView *tableview)
{
    QModelIndex currentIndex = tableview->currentIndex();
    int currentRow = currentIndex.row(); // 获取行号
    //获取模型
    QStandardItemModel* model = qobject_cast<QStandardItemModel*>(tableview->model());
    QStandardItem *item =model->item(currentRow,0);//一开始是0
    //封面
    QIcon image =item->icon();

    ui->pic_display->setIcon(image);
     //右下角显示的歌曲名以及封面
    ui->btn_lrc->setIcon(image);
    ui->song_name->setText(item->data(Qt::UserRole).toString());
    ui->song_name->adjustSize();
    ui->song_name->move(ui->btn_lrc->x()-ui->song_name->width(),ui->btn_lrc->y()+10);
    //歌词显示(右下角)
    ui->song_lrc->setText(ui->song_name->text());
    ui->song_lrc->move(ui->song_name->x(),ui->song_name->y()+ui->song_name->height());
}



MainWindow::~MainWindow() { delete ui; }



